<template>
  <el-dropdown trigger="click">
    <div class="avatar-div">
      <img class="avatar" src="@/assets/images/avatar.gif" alt="avatar" />
      <span class="username">{{ username }}</span>
    </div>
    <template #dropdown>
      <el-dropdown-menu>
        <el-dropdown-item @click="openDialog('lockScreen')">
          <el-icon><Lock /></el-icon>锁定屏幕
        </el-dropdown-item>
        <el-dropdown-item @click="openDialog('updatePassword')">
          <el-icon><User /></el-icon>修改密码
        </el-dropdown-item>
        <el-dropdown-item divided @click="logout">
          <el-icon><SwitchButton /></el-icon>退出登录
        </el-dropdown-item>
      </el-dropdown-menu>
    </template>
  </el-dropdown>
  <UpdatePassword ref="updatePassword" />
  <LockScreen ref="lockScreen" />
</template>
<script setup lang="ts">
import { computed, ref } from "vue";
import { LOGIN_URL } from "@/config";
import { useRouter } from "vue-router";
import { logoutApi } from "@/api/modules/login";
import { useUserStore } from "@/stores/modules/user";
import { ElMessageBox, ElMessage } from "element-plus";
import UpdatePassword from "./UpdatePassword.vue";
import LockScreen from "./LockScreen.vue";

const router = useRouter();
const userStore = useUserStore();
const username = computed(() => userStore.userInfo.name);

// 退出登录
const logout = () => {
  ElMessageBox.confirm("您是否确认退出登录?", "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(async () => {
    // 1.执行退出登录接口
    await logoutApi();

    // 2.清除 Token
    userStore.setToken("");

    // 3.重定向到登陆页
    router.replace(LOGIN_URL);
    ElMessage.success("退出登录成功！");
  });
};

// 打开修改密码和个人信息弹窗
const updatePassword = ref<InstanceType<typeof UpdatePassword> | null>(null);
const lockScreen = ref<InstanceType<typeof LockScreen> | null>(null);
const openDialog = (ref: string) => {
  if (ref == "updatePassword") updatePassword.value?.openDialog();
  if (ref == "lockScreen") lockScreen.value?.openDialog();
};
</script>

<style scoped lang="scss">
.avatar-div {
  display: flex;
  align-items: center;
  width: 80px;
  height: 40px;
  margin-left: 20px;
}
.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
}
.username {
  margin-left: 5px;
  font-size: 15px;
  color: var(--el-header-text-color);
}
</style>
